// pages/ptPay/index.js
const app = getApp()
const util = require('../../utils/util')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    list: '',
    id: "",
    nowDate: "",
    username: "",
    phone: "",
    coupon_id: '',
    allPrice: "",
    collage_sn: '',
    coupon: [],
    pid: "",
    orderId: ''
  },
  checked(e) {
    let idx = e.currentTarget.id
    let couponPrice = this.data.coupon[idx].money//优惠卷
    let originalPrice = this.data.list.course.collage_price //拼团价
    let coupon = this.data.coupon
    if (Number(couponPrice) > Number(originalPrice)) {
      wx.showToast({
        title: '此商品暂不可用优惠卷',
        icon: 'none'
      })
      let arrname = `coupon[${idx}].checked`
      this.setData({
        [arrname]: false
      })
    } else {
      for (var i = 0; i < coupon.length; i++) {
        if (coupon[i].id == e.currentTarget.dataset.id) {
          for (var j = 0; j < coupon.length; j++) {
            if (coupon[j].checked && j != i) {
              coupon[j].checked = false;
              this.setData({
                coupon_id: coupon[idx].id,
                allPrice: originalPrice - couponPrice,//原价 - 优惠卷 = 总价
              });
            } else {
              this.setData({
                coupon_id: '',
                allPrice: originalPrice,//原价 - 优惠卷 = 总价
              })
            }
          }
          coupon[i].checked = !(coupon[i].checked);
        }
        if (coupon[i].checked) {
          this.setData({
            coupon_id: coupon[idx].id,
            allPrice: originalPrice - couponPrice,//原价 - 优惠卷 = 总价
          });
        }
      }
      this.setData({
        coupon: coupon,
      });
    }
  },
  getPhoneNumber: function (e) {
    if (e.detail.errMsg == "getPhoneNumber:fail user deny") {
      wx.showToast({
        title: '已拒绝，获取失败',
        icon: 'none'
      })
    } else {
      wx.login({
        success: (res) => {
          if (res.code) {
            let data = {
              method: 'user.minimobile',
              token: wx.getStorageSync('token'),
              code: res.code,
              iv: e.detail.iv,
              edata: e.detail.encryptedData
            }
            app.api.post('/api/index.html', data).then((res) => {
              if (res.status) {
                this.setData({
                  phone: res.data.mobile
                })
              } else {
                wx.showToast({
                  title: res.msg,
                  icon: 'none'
                })
              }
            })
          } else {
            wx.showToast({
              title: '获取失败',
              icon: 'none'
            })
          }
        }
      })
    }
  },
  onUsername(e) {
    this.setData({
      username: e.detail.value
    })
  },
  onPhone(e) {
    this.setData({
      phone: e.detail.value
    })
  },
  map() {
    var latitude = this.data.list.course.venues.latitude
    var longitude = this.data.list.course.venues.longitude
    wx.getLocation({
      type: 'gcj02', //返回可以用于wx.openLocation的经纬度
      success(res) {
        wx.openLocation({
          latitude: Number(latitude),
          longitude: Number(longitude),
          scale: 18
        })
      }
    })
  },
  pay() {
    let data = {
      method: 'order.orderpay',
      id: this.data.orderId,
      token: wx.getStorageSync('token'),
    }
    app.api.post('/api/index.html', data).then((res) => {
      if (res.status) {
        wx.requestPayment({
          nonceStr: res.data.nonceStr,
          package: res.data.package,
          paySign: res.data.paySign,
          timeStamp: res.data.timeStamp,
          signType: res.data.signType,
          appId: res.data.appId,
          success(res) {
            console.log(res)
            wx.showToast({
              title: '支付成功',
              icon: 'none'
            })
            setTimeout(() => {
              wx.navigateTo({
                url: '/pages/order/index',
              })
            }, 500)
          },
          fail(res) {
            wx.showToast({
              title: '支付失败',
              icon: 'none'
            })
            setTimeout(() => {
              wx.navigateBack({
                delta: 1,
              })
            }, 500)
          }
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })
  },
  onSubmit(e) {
    if (this.data.allPrice == 0) {
      let data = {
        method: 'order.create',
        token: wx.getStorageSync('token'),
        course_id: this.data.id,
        coupon_id: this.data.coupon_id,
        collage_allow: "1",
        username: this.data.username,
        userphone: this.data.phone,
        collage_sn: this.data.collage_sn,//拼团
        pid: this.data.pid//海报分享
      }
      app.api.post('/api/index.html', data).then((res) => {
        if (res.status) {
          wx.showToast({
            title: res.msg,
            icon: 'none'
          })
          setTimeout(() => {
            wx.navigateTo({
              url: '/pages/order/index',
            })
          }, 500)
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none'
          })
        }
      })
    } else {
      let data = {
        method: 'order.create',
        token: wx.getStorageSync('token'),
        course_id: this.data.id,
        coupon_id: this.data.coupon_id,
        collage_allow: "1",
        username: this.data.username,
        userphone: this.data.phone,
        collage_sn: this.data.collage_sn,//拼团
        pid: this.data.pid//海报分享
      }
      app.api.post('/api/index.html', data).then((res) => {
        if (res.status) {
          this.setData({
            orderId: res.data.id
          })
          this.pay()
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none'
          })
        }
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var nowDate = util.formatTime(new Date())
    var formatTimeS = new Date(nowDate).getTime();
    this.setData({
      id: options.id,
      collage_sn: options.collage_sn,
      nowDate: formatTimeS / 1000,
      pid: options.pid
    })
    this.getList()
    this.getUser()
  },
  getList() {
    let data = {
      method: 'course.getzhiinfo',
      id: this.data.id,
      token: wx.getStorageSync('token'),
    }
    app.api.post('/api/index.html', data).then((res) => {
      if (res.status) {
        this.setData({
          list: res.data,
          allPrice: res.data.course.collage_price
        })
        res.data.coupon.forEach(item => {
          item.checked = false
        });
        this.setData({
          coupon: res.data.coupon,
        })
      }
    })
  },
  getUser() {
    let data = {
      method: 'user.info',
      token: wx.getStorageSync('token')
    }
    app.api.post('/api/index.html', data).then((res) => {
      if (res.status) {
        this.setData({
          phone: res.data.mobile,
          username: res.data.realname,
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getList()
    this.getUser()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})